import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchoServer {
    private DatagramSocket socket = null;

    //手动指定服务器的端口号
    public UdpEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }

    //通过start方法来启动服务器
    public void start() throws IOException {
        System.out.println("服务器启动!");
        //服务器一般都是7*24小时运行着
        while(true){
            //1.读取请求并解析
            DatagramPacket requestPacket = new DatagramPacket(new byte[1024], 1024);
            //服务器没收到请求的话就会在这阻塞等待
            socket.receive(requestPacket);

            //2.根据请求计算响应
            String request = new String(requestPacket.getData(), 0, requestPacket.getLength());
            String response = process(request);

            //3.将响应发送给客户端
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(), 0, response.getBytes().length, requestPacket.getAddress(), requestPacket.getPort());
            socket.send(responsePacket);

            //打印日志
            System.out.printf("[%s:%d] req: %s, resp: %s\n", requestPacket.getAddress().toString(), requestPacket.getPort(), request, response);
        }
    }

    public String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer server = new UdpEchoServer(8080);
        server.start();
    }
}
